//
//  PAPersonalViewController.m
//  PAMobileWallet
//
//  Created by shen pu on 13-7-14.
//  Copyright (c) 2013年 Say_smp002. All rights reserved.
//

#import "PAPersonalViewController.h"
#import "PAConstants.h"
#import "PAPersonalCenterView.h"
#import "PASetHomeView.h"
#import "PALoginViewController.h"
#import "PAAddCardViewController.h"
#import "PAChargeMoneyViewController.h"
#import "PAWithdrawalsViewController.h"
#import "PARemitMoneyViewController.h"
#import "PASetHomeViewController.h"
#import "PAHeadPicViewController.h"
#import "PAHomePageViewController.h"
#import "PABankCardView.h"
#import "PAStateType.h"

#import "PADataCenter.h"
#import "NSData+Extend.h"
#import "ASIFormDataRequest.h"
#import <QuartzCore/QuartzCore.h>
#import "PAAsynImageView.h"
@interface PAPersonalViewController ()

@end

@implementation PAPersonalViewController
@synthesize photoImage;

@synthesize bankCardViews;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self){
        personalCenterView = [[PAPersonalCenterView alloc] initWithFrame:RECT_PHONE];
        personalCenterView.parentController = self;
        self.view = personalCenterView;
        
        setHomeView = [[PASetHomeView alloc] initWithFrame:RECT_PHONE];
        setHomeView.parentController = self;
        
        UIView * barView = [[UIView alloc] initWithFrame:CGRectMake(0, (iPhone5?548:460)-24, self.view.frame.size.width, 48/2)];
        barView.backgroundColor = [UIColor clearColor];
        
        UIImageView * barImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"account_upordownbar.png"]];
        barImage.frame = CGRectMake(0, 0, self.view.frame.size.width, 24);
        barImage.backgroundColor = [UIColor clearColor];
        [barView addSubview:barImage];
        
        CGFloat x,y,w,h;
        
        x = 0;  y = 0;  w = 320;  h = 48/2;
        UIButton * goUpButon = [UIButton buttonWithType:UIButtonTypeCustom];
        goUpButon.backgroundColor = [UIColor clearColor];
        goUpButon.frame = CGRectMake(x, y, w, h);
        [goUpButon addTarget:self action:@selector(goUp:) forControlEvents:UIControlEventTouchDragInside|UIControlEventTouchDragOutside|UIControlEventTouchUpInside];
        [barView addSubview:goUpButon];
        
        [self.view addSubview:barView];

        self.bankCardViews = [[NSMutableArray alloc] initWithCapacity:0];
        
        x = 20;  y = 461/2;  w = 280;  h = 230/2 + 14/2;
        cardScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(x, y, w, h)];
        cardScrollView.delegate=self;
        cardScrollView.directionalLockEnabled = YES; //只能一个方向滑动
        cardScrollView.pagingEnabled=YES; //设置分页
        cardScrollView.showsVerticalScrollIndicator=NO;
        cardScrollView.showsHorizontalScrollIndicator=NO;
        cardScrollView.backgroundColor = [UIColor clearColor];
        [personalCenterView addSubview:cardScrollView];
        
        pageControl = [[UIPageControl alloc] init];
        pageControl.frame = CGRectMake(150, 100, 20, 20);//指定位置大小
        pageControl.numberOfPages = [bankCardViews count];//指定页面个数
        pageControl.currentPage = 0; //指定pagecontroll的值，默认选中的小白点（第一个）
        pageControl.hidden = YES;
        [self.view addSubview:pageControl];
        
        PABankCardView * homeScrollerView = [[PABankCardView alloc] initWithCardInfo:nil];
        homeScrollerView.PA_delegate = self;
        
        [self loadSelfBankCardInfos];

        [self showCard:bankCardViews];
        
        homePageViewController = [[PAHomePageViewController alloc] initWithNibName:nil bundle:nil];
        [self.view addSubview:homePageViewController.view];
        [self addChildViewController:homePageViewController];
        
        PADataCenter *dataCenter = [PADataCenter sharedInstance];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginAction:) name:NOT_NeedRelogin object:nil];
        
        [dataCenter.selfInfo addObserver:self forKeyPath:K_availableBalance options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial context:nil];
        [dataCenter.selfInfo addObserver:self forKeyPath:@"baseInfo" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial context:nil];
        [dataCenter.selfInfo addObserver:self forKeyPath:k_bankCardInfos options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial context:nil];
        
        stateType = [PAStateType sharedInstance];
        [stateType setValue:@"0" forKey:@"personalOrCharge"];
        [stateType addObserver:self forKeyPath:@"personalOrCharge" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial context:nil];
    }
    return self;
}

#pragma mark- PAHomeScrollerViewDelegate methods
//添加银行卡(走快捷支付的流程)
- (void)sendHomeScroller:(PABankCardView *)getHomeScroller sendButton:(UIButton *)sender;
{
    [self testNext:personalCenterView.addCardButton];
}

//开通成功，添加卡片

- (void)loadSelfBankCardInfos
{
    for (PABankCardView *oldBankCardView in self.bankCardViews) {
        [oldBankCardView removeFromSuperview];
    }
    [self.bankCardViews removeAllObjects];
    PADataCenter *dataCenter = [PADataCenter sharedInstance];
    NSArray *bankCardInfos = dataCenter.selfInfo.bankCardInfos;
    PABankCardView *blankBankCardV = [[PABankCardView alloc] initWithCardInfo:nil];
    blankBankCardV.PA_delegate = self;
    [cardScrollView addSubview:blankBankCardV];
    [self.bankCardViews addObject:blankBankCardV];
    
    for (PABankCardInfo *tempBankCardInfo in bankCardInfos) {
        PABankCardView *bankCardView = [[PABankCardView alloc] initWithCardInfo:tempBankCardInfo];
        bankCardView.PA_delegate = self;
        bankCardView.bankCardAddButton.enabled = NO;
        [cardScrollView addSubview:bankCardView];
        [bankCardViews insertObject:bankCardView atIndex:bankCardViews.count-1];
    }
    [self layoutCardViews];
}

- (void)showCard:(NSMutableArray *)cardAreray
{
    CGFloat x,y,w,h;
    
    x = 0;  y = 0;  w = 280;  h = 230/2 + 14/2;

    if ([cardAreray count] < 1)
    {
        PABankCardView * lastView = [[PABankCardView alloc] initWithFrame:CGRectMake(x, y, w, h)];
        lastView.PA_delegate = self;
        lastView.bankCardBgImage.image = [UIImage imageNamed:@"account _addcard.png"];
        lastView.bankCardAddButton.enabled = YES;
        lastView.bankCardImage.hidden = YES;
        lastView.bankCardNameImage.hidden = YES;
        lastView.bankCardNumLable.hidden = YES;
        lastView.bankCardNameLable.hidden = YES;
        [cardScrollView addSubview:lastView];
        [bankCardViews addObject:lastView];
    }
    
    [self layoutCardViews];
}

-(void)layoutCardViews
{
    pageControl.numberOfPages = [bankCardViews count];//指定页面个数

	int num=0;
    for(int i=0; i<[bankCardViews count]; i++)
    {
        UIView * view = [bankCardViews objectAtIndex:i];
		CGRect sliRect=view.frame;
		sliRect.origin.x = num * 280;
		view.frame = sliRect;
		num++;
	}
    
    cardScrollView.contentSize=CGSizeMake(280 * num, 230/2);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int page = cardScrollView.contentOffset.x/280;
    pageControl.currentPage = page;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	//
}

- (void)goUp:(UIButton *)sender
{
    [homePageViewController startAnimition:homePageViewController.view sendState:@"down"];
}

//判断是不是homecontroller在个人中心上
- (void)checkUpOrDown:(NSString *)getStr
{
    [homePageViewController startAnimition:homePageViewController.view sendState:getStr];
}


//检测一下卡的数组是否为空
- (NSArray *)checkCardInfo:(id)sender
{
    if (!dataCenterT)
    {
        dataCenterT = [PADataCenter sharedInstance];
    }
    NSArray * bankCardInfos = dataCenterT.selfInfo.bankCardInfos;
    
    return bankCardInfos;
}
- (void)testNext:(id)sender
{
    int tag = [(UIButton *)sender tag];
    PABaseViewController *controller = nil;
    switch (tag)
    {
        case 0:
            if (!addCardController)
            {
                addCardController = [[PAAddCardViewController alloc] initWithNibName:nil bundle:nil];
                addCardController.parentController = self;
            }
            [stateType setValue:@"10" forKey:@"personalOrCharge"];
            controller = addCardController;
            break;
        case 1:    // 1:表示充值  2：表示提现
        {
            NSArray * getArray = [self checkCardInfo:nil];
            if ([getArray count] > 0 && pageControl.currentPage < [getArray count])
            {
                [stateType setValue:@"30" forKey:@"personalOrCharge"];
                [self gotoAnotherController:1 sendCardArray:getArray lastCardArray:nil];
            }
            else
            {
                if ([getArray count]==0) {
                    [stateType setValue:@"20" forKey:@"personalOrCharge"];

                    [self gotoAnotherController:1 sendCardArray:nil lastCardArray:@"空"];
                }
                else{
                    [self gotoAnotherController:1 sendCardArray:getArray lastCardArray:@"非空"];
                }
                //[self testNext:personalCenterView.addCardButton];
            }
        }
            break;
        case 2:   // 先判断是否有卡  有：去充值界面  无：去开通快捷支付界面
        {
            NSArray * getArray = [self checkCardInfo:nil];
            if ([getArray count] > 0 && pageControl.currentPage < [getArray count])
            {
                [stateType setValue:@"30" forKey:@"personalOrCharge"];
                [self gotoAnotherController:2 sendCardArray:getArray lastCardArray:nil];
            }
            else
            {
                if ([getArray count]==0) {
                    [stateType setValue:@"20" forKey:@"personalOrCharge"];
                    [self gotoAnotherController:2 sendCardArray:nil lastCardArray:@"空"];
                }
                else{
                    [self gotoAnotherController:2 sendCardArray:getArray lastCardArray:@"非空"];
                }

                /*
                [stateType setValue:@"20" forKey:@"personalOrCharge"];
                [self gotoAnotherController:2 sendCardArray:getArray lastCardArray:@"非空"];
                //[self testNext:personalCenterView.addCardButton];
                 */
            }
        }
            break;
        case 3:
            if (!remitMoneyController)
            {
                remitMoneyController = [[PARemitMoneyViewController alloc] initWithNibName:nil bundle:nil];
                remitMoneyController.parentController = self;
            }
            remitMoneyController.targetInfo = nil;
            controller = remitMoneyController;
            break;
        case 4:{
            PASetHomeViewController *setHomeController = [[PASetHomeViewController alloc] initWithNibName:nil bundle:nil];
            setHomeController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.navigationController presentModalViewController:setHomeController animated:YES];
            return;
        }
            break;
        case 5:
            if (!headPicController)
            {
                headPicController = [[PAHeadPicViewController alloc] initWithNibName:nil bundle:nil];
                headPicController.parentController = self;
            }
            
            [self getphoto:nil getType:HEADPICMODE_change];
            break;
        default:
            break;
    }
    
    if (tag == 0 || tag == 3 || tag == 4)
    {
        [self.navigationController pushViewController:controller animated:YES];
    }
}

// 跳转到 充值 或者提现 或者开通快捷
- (void)gotoAnotherController:(int)sender sendCardArray:(NSArray *)getCardArray lastCardArray:(NSString *)lastArray
{
    PABaseViewController * controller = nil;
    if (!chargeMoneyController)
    {
        chargeMoneyController = [[PAChargeMoneyViewController alloc] initWithNibName:nil bundle:nil];
        chargeMoneyController.parentController = self;
    }
    
    /*
    if (lastArray != nil)
    {
//        [chargeMoneyController sendBankCardInfo:[getCardArray objectAtIndex:0]];
        chargeMoneyController.selectedBankCardInfo = [getCardArray objectAtIndex:0];
    }
    else
    {
//        [chargeMoneyController sendBankCardInfo:[getCardArray objectAtIndex:pageControl.currentPage]];
        chargeMoneyController.selectedBankCardInfo = [getCardArray objectAtIndex:pageControl.currentPage];
    }
     */
    
    controller = chargeMoneyController;

    if (sender == 1)
    {
        [chargeMoneyController sendNavTitle:@"充值"];
    }
    else if(sender == 2)    //  现在都是进充值，提现界面。 因为同样界面，所以进同一个界面
    {
        [chargeMoneyController sendNavTitle:@"提现"];
    }
    
    if ([lastArray isEqualToString:@"空"]) {
        [self.navigationController pushViewController:controller animated:NO];
        [chargeMoneyController pushAddCardView:nil];
        
    }else if ([lastArray isEqualToString:@"非空"])
    {
        chargeMoneyController.selectedBankCardInfo = [getCardArray objectAtIndex:0];
        [self.navigationController pushViewController:controller animated:YES];
    }
    else
    {
        chargeMoneyController.selectedBankCardInfo = [getCardArray objectAtIndex:pageControl.currentPage];
        [self.navigationController pushViewController:controller animated:YES];
    }

}

- (void)getphoto:(UIButton *)sender getType:(HEADPICMODE)headType
{
    UIActionSheet *choosePhotoActionSheet;
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        choosePhotoActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"请选择上传方式", @"")
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"cancel", @"")
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:NSLocalizedString(@"拍照选择", @""),NSLocalizedString(@"从相册选择", @""), nil];
    }
    else
    {
        choosePhotoActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"choose_photo", @"")
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"cancel", @"")
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:NSLocalizedString(@"拍照选择", @""),NSLocalizedString(@"从相册选择", @""), nil];
    }
    
    [choosePhotoActionSheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	NSUInteger sourceType = 0;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        switch (buttonIndex)
        {
            case 0:
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 1:
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 2:
                return;
        }
    }
    else
    {
        if (buttonIndex == 2)
        {
            return;
        }
        else
        {
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
    }
    
	UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
	imagePickerController.delegate = self;
	imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
	//[self presentModalViewController:imagePickerController animated:YES];
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
	self.photoImage = [info objectForKey:UIImagePickerControllerEditedImage];
    
    personalCenterView.headIV.image = self.photoImage;
//    [personalCenterView.headIV setHeadImage:self.photoImage];
    personalCenterView.headIV.layer.masksToBounds=YES;
    personalCenterView.headIV.layer.cornerRadius=74.0/2;//最重要的是这个地方要设成imgview高的一半
    
    NSData *imageData = UIImageJPEGRepresentation(self.photoImage, 0.5);//UIImagePNGRepresentation(self.photoImage);
    NSString *base64String = [imageData base64Encoding];
    
    NSMutableDictionary * postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType:@"op_change_head_image",k_imageType:[NSNumber numberWithInt:1],k_headImage:base64String}];
    [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)showSecleteView:(HOME_TYPE)type
{
    PABaseView *toView = (type == HOME_TYPE_Page) ? personalCenterView : setHomeView;
    
    [UIView transitionFromView:self.view toView:toView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished) {
        self.view = toView;
    }];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    personalCenterView.rechargeButton.titleLabel.textColor = PERSONAL_COLOR;
    personalCenterView.extractButton.titleLabel.textColor = PERSONAL_COLOR;

    [self loadSelfBankCardInfos];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)loginAction:(NSDictionary *)dic
{
//    NSString *loginId = [dic objectForKey:k_loginId];
//    [[PADataCenter sharedInstance] loadCacheForLoginId:loginId];
    NSMutableDictionary *postingDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [postingDic setObject:@"op_login" forKey:k_operationType];
    [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
}

#pragma mark - PANetworkDelegate
- (void)paRequestRespons:(NSDictionary *)responsDic userInfo:(NSDictionary *)userInfo
{
    NSString *op = [responsDic objectForKey:k_operationType];
    if ([op isEqualToString:@"op_login"]) {
        PADataCenter *dataCenter = [PADataCenter sharedInstance];
        [dataCenter updateLoginInfoDic:responsDic];
        
        NSMutableDictionary *postingDic = [NSMutableDictionary dictionaryWithDictionary:@{k_operationType:@"op_query_last_payment_info",k_loginId:dataCenter.selfInfo.baseInfo.account,@"pageIndex":[NSNumber numberWithInt:1],@"pageSize":[NSNumber numberWithInt:100]}];
        [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
        
        [self checkUpOrDown:@"down"];
        
        [self dismissModalViewControllerAnimated:YES];
    }
    if ([op isEqualToString:@"op_query_last_payment_info"]) {
        /*
         * 应该先更新数据 再 又 KVO 形式刷新 UI
         */
        [personalCenterView refreshUIData];
    }
    if ([op isEqualToString:@"op_change_head_image"])
    {
        PAUserInfo * userInfo = [[PAUserInfo alloc] initWithDic:[responsDic objectForKey:k_userInfo]];
        [PADataCenter sharedInstance].selfInfo.baseInfo = userInfo;
    }
}
- (void)reloginAction:(id)sender
{
    NSDictionary *dic = [(NSNotification *)sender object];
    BOOL isNeedHome = [[dic objectForKey:@"isNeedHome"] boolValue];
    if (isNeedHome) {
        if (nil == homePageViewController) {
            homePageViewController = [[PAHomePageViewController alloc] initWithNibName:nil bundle:nil];
        }
        [homePageViewController startAnimition:homePageViewController.view sendState:@"down"];
    }
    PALoginViewController *loginVC = [[PALoginViewController alloc] initWithNibName:nil bundle:nil];
    loginVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:loginVC animated:YES];
    
}
#pragma mark - KVO 监听 数据变化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    PADataCenter *dataCenter = [PADataCenter sharedInstance];
    if ([keyPath isEqualToString:K_availableBalance]) {
        personalCenterView.yueValueLabel.text = [NSString stringWithFormat:@"%.2f",dataCenter.selfInfo.availableBalance];
    }else if ([keyPath isEqualToString:@"baseInfo"]){
        NSLog(@"personViewController  = baseInfo:%@",dataCenter.selfInfo.baseInfo);
        [personalCenterView.headIV setImgUrl:dataCenter.selfInfo.baseInfo.headImageUrl key:dataCenter.selfInfo.baseInfo.phoneNum digest:dataCenter.selfInfo.baseInfo.headImageDigest];
        
        CGFloat x, y, w, h;
        CGSize size = personalCenterView.frame.size;
        CGFloat space = 10;
        
        w = h = 70;
        y = space;
        x = (size.width - w) / 2;
        
        if (!dataCenter.selfInfo.baseInfo.headImageUrl) {
            personalCenterView.whiteSycleBgIV.hidden = YES;
            personalCenterView.headIV.frame = CGRectMake(x-3, y-3, w+7, h+7);
        }else{
            personalCenterView.whiteSycleBgIV.hidden = NO;
            personalCenterView.headIV.frame = CGRectMake(x+5, y+4, w-10, h-10);
        }
        personalCenterView.headIV.cornerRadius = personalCenterView.headIV.frame.size.height/2;
        personalCenterView.nameLabel.text = [[PADataCenter sharedInstance] selfInfo].baseInfo.realName;
    }else if([keyPath isEqualToString:@"bankCardInfos"]){
        [self  loadSelfBankCardInfos];
        personalCenterView.cardNOValueLabel.text = [NSString stringWithFormat:@"%d",dataCenter.selfInfo.bankCardInfos.count];
    }else if ([keyPath isEqualToString:@"personalOrCharge"]){
        NSLog(@"stateType.personalOrCharge --------- %@",stateType.personalOrCharge);
    }
    else{
        /*
         * do nothing
         */
    }
}


@end
